<template>
  <div class="auth-product partDetailsBox">
    <el-container class="partDetails">
      <!-- 列表 -->
      <el-header style="height: auto;">
        <tabs
          v-if="![7, null].includes(orderStatus)"
          :tabs-arr="tabSliceList"
          @returnIndex="tabsHandle"
          class="tab-info" />
      </el-header>
      <div v-if="activeIndex === 0 && orderStatus !== 7">
        <RecordInfo
          :record-form="recordFormDetail"
          :record-data="headerInfo">
          <span
            slot="orderAmount"
            style="color:red;">{{ headerInfo.orderAmount }}</span>
            <!-- <template v-slot:recordInfoslot="slotProp">
            <div class="solt-info">
              <span class="left-span">
                销售产品总数
                <span class="right-span">{{ headerInfo.prodTotalCount }}</span>
              </span>
              <span>
                品种数
                <span>{{ headerInfo.prodTypeCount }}</span>
              </span>
              <span>
                金额合计 （元）:
                <span>
                  <span class="price">{{ headerInfo.orderAmount | getFormatterPrice }}</span>
                </span>
              </span>
            </div>
          </template> -->
        </RecordInfo>
        <SearchForm
          :data="detailsSearchForm"
          @searchForm="searchForm"
          @resetForm="resetForm"
          :submit-loading='submitLoading'
        />
        <el-editable
          class="hospital-edit-box"
          :data="pssCompareHspList"
          :row-style="getRowStyle"
          :span-method="pssSpanMethod"
          height="400"
          v-loading="tableLoading"
          :columns="partDetailsTableData"
        >
          <template
            slot="default-index"
            slot-scope="scope">
            <span v-if="!(scope.$index % 2)">{{ scope.$index / 2 + 1 }}</span>
          </template>
          <template
            slot="default-registrationNumber"
            slot-scope="scope">
            <div>
              <cell-registration
                :key="scope.row.registrationNumber"
                :regis-no="scope.row.registrationNumber"
                :content="'注册证已过期，点击查看详细信息'"
                :status="scope.row.isNoExpire"
                :regis-data="scope.row.registrationInfo"
              />
            </div>
            <!-- <el-button
              :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
              v-html="regisNoButton(scope.row)"
              type="text"
              @click="showPdfRegistion(scope.row.registrationId)"
            /> -->
          </template>
        </el-editable>
        <el-footer>
          <el-pagination
            class="pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="curPage"
            :page-sizes="PAGE_NUMBER"
            :page-size="pageSize"
            :layout="PAGINATION_LAYOUT"
            :total="totalElements"
          />
        </el-footer>
      </div>
      <div v-if="activeIndex === 1 && orderStatus !== 7">
        <RecordInfo
          :record-form="reciveDetailInfo"
          :record-data="headerInfo" />
        <div
          v-for="(item,index) in deliveryDetailList"
          :key="index">
          <RecordInfo
            :record-form="reciveDetailInfoOrder"
            :record-data="item">
            <span
              slot="deliverTotalAmount"
              style="color:red;">{{ item.deliverTotalAmount }}</span>
          </RecordInfo>
          <!-- <div class="order-list-info">
            <span>
              发货单号
              <span>{{ item.deliverCode }}</span>
            </span>
            <span>
              发货时间
              <span>{{ item.deliverTime }}</span>
            </span>
            <span>
              发货人
              <span>{{ item.deliverer }}</span>
            </span>
          </div> -->
          <!-- <div class="order-list-info">
            <span>
              发货产品总数
              <span class="recive-count add-color">{{ item.deliverCount }}</span>
            </span>
            <span>
              品种数
              <span class="add-color">{{ item.deliverTypeCount }}</span>
            </span>
            <span>
              金额合计 （元）
              <span class="add-price">{{ item.deliverTotalAmount | getFormatterPrice }}</span>
            </span>
          </div> -->
          <el-editable
            class="hospital-edit-box"
            :data="item.deliverProductList.content"
            height="400"
            v-loading="tableLoading"
            :columns="receiptDetailsTable"
          >
            <template
              slot="default-deliveredCount"
              slot-scope="{row}">
              <el-button
                type="text"
                @click="showReciveInfoDialog(index,row,1)"
              >{{ row.deliveredCount }}</el-button>
            </template>
            <template
              slot="default-refuseCount"
              slot-scope="{row}">
              <el-button
                type="text"
                @click="showReciveInfoDialog(index,row,2)">{{ row.refuseCount }}</el-button>
            </template>
            <template
              slot="default-registrationNumber"
              slot-scope="scope">
              <div>
                <cell-registration
                  :key="scope.row.registrationNumber"
                  :regis-no="scope.row.registrationNumber"
                  :content="'注册证已过期，点击查看详细信息'"
                  :status="scope.row.isNoExpire"
                  :regis-data="scope.row.registrationInfo"
                />
              </div>
              <!-- <el-button
                :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
                @click="showPdfRegistion(scope.row.registrationId)"
                v-html="regisNoButton(scope.row)"
                type="text"
              /> -->
            </template>
          </el-editable>
          <el-pagination
            class="pagination"
            @size-change="pageListHandleSizeChange($event,index)"
            @current-change="pageListHandleCurrentChange($event,index)"
            :current-page="pageList[index].curPage"
            :page-sizes="pageList[index].PAGE_NUMBER"
            :page-size="pageList[index].pageSize"
            :layout="pageList[index].PAGINATION_LAYOUT"
            :total="item.deliverProductList.totalElements"
          />
        </div>
      </div>
      <div v-show="orderStatus === 7">
        <RecordInfo
          :record-form="recordFormDetail"
          :record-data="headerInfo">
          <span
            slot="orderAmount"
            style="color:red;">{{ headerInfo.orderAmount }}</span>
            <!-- <template v-slot:recordInfoslot="slotProp">
            <div class="solt-info">
              <span class="left-span">
                医院采购产品总数
                <span class="right-span">{{ headerInfo.prodTotalCount }}</span>
              </span>
              <span>
                品种数
                <span>{{ headerInfo.prodTypeCount }}</span>
              </span>
              <span>
                金额合计 （元）:
                <span>
                  <span class="price">{{ headerInfo.orderAmount | getFormatterPrice }}</span>
                </span>
              </span>
            </div>
          </template> -->
        </RecordInfo>
        <SearchForm
          :data="detailsSearchFormFailed"
          @searchForm="searchForm"
          @resetForm="resetForm"
          :submit-loading='submitLoading'
        />
        <el-editable
          class="hospital-edit-box"
          :data="pssCompareHspList"
          :row-style="getRowStyle"
          :span-method="pssSpanMethod"
          height="400"
          v-loading="tableLoading"
          :columns="partFailtedDetailsTableData"
        >
          <template
            slot="default-index"
            slot-scope="scope">
            <span v-if="!(scope.$index % 2)">{{ scope.$index / 2 + 1 }}</span>
          </template>
          <template
            slot="default-pssRegistNo"
            slot-scope="scope">
            <div>
              <cell-registration
                :key="scope.row.pssRegistNo"
                :regis-no="scope.row.pssRegistNo"
                :content="'注册证已过期，点击查看详细信息'"
                :status="scope.row.isNoExpire"
                :regis-data="scope.row.registrationInfo || null"
              />
            </div>
            <!-- <el-button
              :disabled="!scope.row.pssRegistNo||!scope.row.pssRegistId"
              v-html="regisNoButton(scope.row, ['pssRegistNo', 'pssRegistId'])"
              type="text"
              @click="showPdfRegistion(scope.row.pssRegistId)"
            /> -->
          </template>
          <template
            slot="default-hspRegistNo"
            slot-scope="scope">
            <div>
              <cell-registration
                :key="scope.row.hspRegistNo"
                :regis-no="scope.row.hspRegistNo"
                :content="'注册证已过期，点击查看详细信息'"
                :status="scope.row.isNoExpire"
                :regis-data="scope.row.registrationInfo"
              />
            </div>
            <!-- <el-button
              :disabled="!scope.row.hspRegistNo||!scope.row.hspRegistId"
              v-html="regisNoButton(scope.row, ['hspRegistNo', 'hspRegistId'])"
              type="text"
              @click="showPdfRegistion(scope.row.hspRegistId)"
            /> -->
          </template>
        </el-editable>
        <el-footer>
          <el-pagination
            class="pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="curPage"
            :page-sizes="PAGE_NUMBER"
            :page-size="pageSize"
            :layout="PAGINATION_LAYOUT"
            :total="totalElements"
          />
        </el-footer>
      </div>
    </el-container>
    <el-dialog
      :title="isRejection?'拒收记录':'发货记录'"
      width="1200px"
      :visible.sync="dialogPopupVisible"
      @close="closeDialog"
      class="dialog-info"
    >
      <el-editable
        :data="dialogGetReciveOneList"
        v-loading="tableLoading"
        :columns="dialogReceiptDetails"
      >
        <template
          slot="default-registrationNumber"
          slot-scope="scope">
          <div>
            <cell-registration
              :key="scope.row.registrationNumber"
              :regis-no="scope.row.registrationNumber"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.isNoExpire"
              :regis-data="scope.row.registrationInfo"
            />
          </div>
          <!-- <el-button
            :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
            v-html="regisNoButton(scope.row)"
            @click="showPdfRegistion(scope.row.registrationId)"
            type="text"
          /> -->
        </template>
      </el-editable>
      <el-editable
        :data="dialogReciveInfoList"
        height="400"
        class="center-table"
        v-loading="tableLoading"
        :columns="reciveTableInside"
      />
      <el-pagination
        class="pagination"
        @size-change="dialogHandleSizeChange"
        @current-change="dialogHandleCurrentChange"
        :current-page="dialogPage.curPage"
        :page-sizes="dialogPage.PAGE_NUMBER"
        :page-size="dialogPage.pageSize"
        :layout="dialogPage.PAGINATION_LAYOUT"
        :total="dialogPage.totalElements"
      />
    </el-dialog>
    <follow-goods
      :is-show-follow-goods-list="isShowFollowGoodsList"
      :follow-goods-list-data="FollowGoodsListData"
      :role-type="roleType"
      :settle="settle"
      @cancelDialog="cancelDialog"
    />
  </div>
</template>

<script>
import {
  partDetailsTableData,
  partFailtedDetailsTableData,
  receiptDetailsTable,
  detailTabsArr,
  recordFormDetail,
  reciveDetailInfo,
  reciveTableInside,
  dialogReceiptDetails,
  ORDER_STATUS_TEXT,
  detailsSearchForm,
  reciveDetailInfoOrder,
  detailsSearchFormFailed
} from './const'
import { getFormatterPrice } from '@const/filter'
import tabs from '@components/tabs/index.vue'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import { attrItemList } from '@const/orderCenterApi'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import {
  getHospitalPurchaseOrderItem,
  wscSaleOrderOrderDetailReceiveFailed, // 销售补货管理--批发/寄售--获取销售订单接收失败详情信息
  getHospitalPurchaseOrderList,
  getByBsAddress,
  distributorWscSaleOrderOrder,
  distributorWscSaleOrderDeliverList,
  distributorwscSaleOrderDeliverListById,
  distributorWscSaleOrderDeliverSweepRecord,
  wscSaleOrderPeerList
} from '@const/beforeSettleApi'
import {
  enumSelectorComCategoryNameList,
  getCertificate
} from '@const/productCenterApiV2'
import ElEditable from '@components/el-editable'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { regisNoButton, showPdfRegistion } from '@const/agencySaas'
import followGoods from '@/moduleComponents/beforeSettle/followGoodsNote'
import SearchForm from '@components/businesscomponents/search'
export default {
  components: { ElEditable, tabs, RecordInfo, followGoods, CellRegistration, SearchForm },
  data () {
    return {
      orderStatus: Number(this.$route.query.orderStatus),
      isRejection: false,
      // 表单Loading
      formLoading: false,
      // 表格Loading
      tableLoading: false,
      // 表头
      partDetailsTableData,
      partFailtedDetailsTableData,
      // 表格数据
      pssCompareHspList: [],
      // 表单编辑默认值
      formdata: {},
      recordFormDetail,
      // 表单 详情展示内容-table
      // 部分收货表格
      receiptDetailsTable,
      // 详情ID
      detailsId: this.$route.query.id,
      // 详情tab
      detailTabsArr,
      curPage: 1, // 当前页
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0, // 总共的条数
      dialogPage: {
        curPage: 1, // 当前页
        PAGE_NUMBER, // 页码数组
        PAGINATION_LAYOUT, // 页码功能布局
        pageSize: PAGE_NUMBER[0], // 一页的数量
        totalElements: 0 // 总共的条数
      },
      insideTableLoading: false,
      deliveryDetailList: [],
      activeIndex: 0,
      reciveDetailInfo,
      dialogPopupVisible: false,
      reciveTableInside,
      dialogReceiptDetails,
      headerInfo: {},
      pageList: [],
      dialogReciveInfoList: [],
      dialogGetReciveOneList: [],
      getReciveListId: '',
      isShowFollowGoodsList: false,
      FollowGoodsListData: [],
      roleType: 2,
      settle: 1, // 1-结算前，2-结算后
      detailsSearchForm,
      submitLoading: false,
      searchQuery: {},
      reciveDetailInfoOrder,
      detailsSearchFormFailed
    }
  },
  filters: {
    getFormatterPrice
  },
  computed: {
    tabSliceList () {
      if (
        Number(this.$route.query.orderStatus) !== 3 &&
        Number(this.$route.query.orderStatus) !== 4
      ) {
        let detailTabsArr = cloneDeep(this.detailTabsArr)
        detailTabsArr[1].disabled = true
        return detailTabsArr
      } else {
        let detailTabsArr = cloneDeep(this.detailTabsArr)
        return detailTabsArr
      }
    },
    isFaild () {
      return this.orderStatus === 7
    },
    detailUrl () {
      return this.isFaild ? wscSaleOrderOrderDetailReceiveFailed : distributorWscSaleOrderOrder
    }
  },

  mounted () {
    let status = Number(this.$route.query.orderStatus)
    let arr = []
    if (status === 3 || status === 4) {
      arr = [
        { type: 'button', val: '返回', handle: this.back },
        { type: 'primary', val: '查看随货同行单', handle: this.lookFollowGoodsNote }
      ]
    } else {
      arr = [
        { type: 'button', val: '返回', handle: this.back }
      ]
    }
    const btn = {
      type: 'btn',
      arr: arr
    }
    this.$store.commit('changeLayoutHandle', btn)
    this.list(this.detailUrl)
    if (
      Number(this.$route.query.orderStatus) === 3 ||
      Number(this.$route.query.orderStatus) === 4
    ) {
      this.getReciveList()
    }
  },

  methods: {
    regisNoButton,
    showPdfRegistion,
    // 查询
    searchForm (val) {
      this.searchQuery = val
      this.list(this.detailUrl)
    },
    // 重置
    resetForm (val) {
      this.curPage = 1
      this.searchQuery = val
      this.list(this.detailUrl)
    },
    // 查看随货同行单
    lookFollowGoodsNote () {
      this.$axios
        .$post(wscSaleOrderPeerList, {
          purchaseOrderId: this.headerInfo.purchaseOrderId,
          saleOrderId: this.headerInfo.saleOrderId,
          roleType: this.roleType // 登录角色（1-医院 2-配送商)
        })
        .then(res => {
          let data = res.payload || []
          // 如果有多个随货同行单，就弹框让其选择
          // 如果只有一个，直接弹出
          if (data.length > 0) {
            this.FollowGoodsListData = data
            this.isShowFollowGoodsList = true
          } else {
            this.$message({
              type: 'warning',
              message: '此订单还没有随货同行单！'
            })
          }
        })
    },
    cancelDialog () {
      this.isShowFollowGoodsList = false
    },
    // 获取订单列表详情
    list (url) {
      // Loading加载开始
      this.tableLoading = true
      // 请求列表数据
      this.$axios
        .$post(url, {
          saleOrderId: this.$route.query.id,
          page: this.curPage,
          pageSize: this.pageSize,
          orderType: 2,
          ...this.searchQuery
        })
        .then(res => {
          let obj = hasIn(res, 'payload') ? res.payload : {}
          for (let key in obj) {
            if (key !== 'saleProductList') {
              if (!obj[key]) {
                obj[key] = `--`
              }
              if (key === 'orderStatus') {
                this.orderStatus = obj[key]
                obj[key] = ORDER_STATUS_TEXT[obj[key]]
              }
              this.$set(this.headerInfo, [key], obj[key])
            } else if (key === 'saleProductList') {
              // 接收失败和其他状态接口和数据不一样，需要分别处理
              this.pssCompareHspList = this.getPssCompareHspList(obj[key].content)
              this.totalElements = obj[key].totalElements
            }
          }
          this.headerInfo.orderAmount = Number(this.headerInfo.orderAmount) ? Number(this.headerInfo.orderAmount).toFixed(2) : '0.00'
          this.tableLoading = false
        })
        .finally(res => {
          this.tableLoading = false
        })
    },
    // 获取发货信息
    getReciveList () {
      this.$axios({
        method: 'post',
        url: distributorWscSaleOrderDeliverList,
        data: {
          page: 1,
          pageSize: 20,
          saleOrderId: this.$route.query.id,
          orderType: 2
        }
      }).then(res => {
        let arr = hasIn(res, 'data.payload') ? res.data.payload : []
        this.deliveryDetailList = arr
        this.deliveryDetailList.forEach(item => {
          item.deliverTotalAmount = Number(item.deliverTotalAmount) ? Number(item.deliverTotalAmount).toFixed(2) : '0.00'
        })
        this.pageList = this.deliveryDetailList.map(item => {
          return {
            curPage: 1, // 当前页
            PAGE_NUMBER, // 页码数组
            PAGINATION_LAYOUT, // 页码功能布局
            pageSize: PAGE_NUMBER[0] // 一页的数量
          }
        })
      })
    },
    // 发货信息列表页码更改触发
    getReciveListById (index) {
      this.$axios({
        method: 'post',
        url: distributorwscSaleOrderDeliverListById,
        data: {
          page: this.pageList[index].curPage,
          pageSize: this.pageList[index].pageSize,
          deliverId: this.deliveryDetailList[index].deliverId,
          orderType: 2
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        let arr = obj.content
        this.deliveryDetailList[index].deliverProductList.content = arr
      })
    },
    // 获取弹框发货信息详情
    getReciveInfo (num) {
      this.$axios({
        method: 'post',
        url: distributorWscSaleOrderDeliverSweepRecord,
        data: {
          page: this.dialogPage.curPage,
          pageSize: this.dialogPage.pageSize,
          deliverDetailId: this.getReciveListId,
          orderType: 2,
          checkStatus: num
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.dialogReciveInfoList = obj.content
        this.dialogPage.totalElements = obj.totalElements
      })
    },
    // 点击发货数量获取发货信息详情的弹框
    showReciveInfoDialog (index, date, num) {
      if (num === 2) {
        this.isRejection = true
      } else {
        this.isRejection = false
      }
      this.dialogPopupVisible = true
      this.dialogGetReciveOneList.push(date)
      this.getReciveListId = date.deliverDetailId
      this.getReciveInfo(num)
    },
    // 收货信息列表页条数更改
    pageListHandleSizeChange ($event, index) {
      this.pageList[index].pageSize = $event
      this.getReciveListById(index)
    },
    // 收货信息列表页码更改
    pageListHandleCurrentChange ($event, index) {
      this.pageList[index].curPage = $event
      this.getReciveListById(index)
    },
    // 关闭弹框
    closeDialog () {
      this.dialogPopupVisible = false
      this.dialogGetReciveOneList = []
      this.getReciveListId = ''
    },
    // 弹框分页条数更改
    dialogHandleSizeChange (pageSize) {
      this.dialogPage.pageSize = pageSize
      this.getReciveInfo()
    },
    // 弹框页码更改
    dialogHandleCurrentChange (curPage) {
      this.dialogPage.curPage = curPage
      this.getReciveInfo()
    },
    /**
     * @des 获取产品信息对比list
     */
    getPssCompareHspList (list) {
      let result = []
      list = list || []
      if (this.isFaild) {
        list.forEach(e => {
          let hspData = {
            saleDetailCode: '医院产品信息',
            pssProdCode: e.hspProdCode,
            pssProdName: e.hspProdName,
            pssProdSpecs: e.hspProdSpecs,
            pssProdModel: e.hspProdModel,
            pssProdMinUnit: e.hspProdMinUnit,
            pssManufacturer: e.hspManufacturer,
            pssRegistNo: e.hspRegistNo,
            isNoExpire: null,
            registrationInfo: null,
            price: e.price,
            purchaseCount: e.purchaseCount,
            detailAmount: e.detailAmount,
            remarks: e.remarks,
            hspProdBigCategory: e.hspProdBigCategory
          }
          result.push(e)
          result.push(hspData)
        })
        return result
      } else {
        list.forEach(e => {
          let info = e.hspItemInfo || {}
          let hspData = {
            saleDetailCode: '医院产品信息',
            prodCustomCode: info.prodCustomCode, // prodCustomCode
            prodName: info.prodName,
            prodSpecs: info.prodSpecs,
            prodModel: info.prodModel,
            minUnit: info.minUnit,
            registrationNumber: info.registrationNumber,
            price: info.price,
            isNoExpire: null,
            registrationInfo: null,
            manufacturer: info.manufacturer, // 生产厂家
            saleCount: info.purchaseCount,
            detailAmount: info.detailAmount,
            remarks: info.remarks,
            prodBigCategory: info.prodBigCategory
          }
          result.push(e)
          result.push(hspData)
        })
        return result
      }
    },
    // 合并单元格
    pssSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2) {
        if (column.property === 'saleDetailCode') {
          return [1, 2]
        }
        if (column.property === 'relationDetailCode') {
          return [0, 0]
        }
        if (columnIndex === 0) {
          return [0, 0]
        }
      } else {
        if (columnIndex === 0) {
          return [2, 1]
        }
      }
    },
    // 奇数行灰色
    getRowStyle ({ row, rowIndex }) {
      if (rowIndex % 2) {
        return 'color: #A7B1C7;'
      }
    },
    // 展开收起
    handleChange (val) {
      console.log(val)
    },

    // 页码更改
    handleSizeChange (size) {
      this.curPage = 1
      this.pageSize = size
      this.list(this.detailUrl)
    },

    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.list(this.detailUrl)
    },
    // tab切换
    tabsHandle (index) {
      this.activeIndex = index
    },
    // 点击返回
    back () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less">
.partDetailsBox {
  height: 100%;
  .partDetails {
    display: flex;
    height: 100%;
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
  .tab-info {
    //  padding-bottom: 10px;
  }
  .order-list-info {
    padding-left: 16px;
    height: 30px;
    line-height: 30px;
    span {
      margin-right: 30px;
      font-size: 14px;
      span {
        padding: 0 8px;
        color: black;
        font-size: 14px;
      }
      .add-color {
        color: blue;
      }
      .add-price {
        color: red;
      }
    }
  }
  .dialog-info {
    .center-table {
      margin-top: 46px;
    }
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
